//
//  ComposeViewController.swift
//  weibo
//
//  Created by 上官风雨 on 15/11/18.
//  Copyright © 2015年 上官风雨. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
import AFNetworking

class ComposeViewController: UIViewController {
    @objc private func pictureSelect(){
        
        selectVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(224 + 80 + 40)
        }
        
    }
    
    //关闭的方法
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    //发布的点击方法
    @objc private func send(){
        
//        let urlString = "https://api.weibo.com/2/statuses/update.json"
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        guard let token = UserAccountViewModel().token else{
            SVProgressHUD.showInfoWithStatus("客观,您还没有给小费(登录)呢...")
            return
        }
        
        let parameters = ["access_token":token,"status":textView.text]
        let imageData = UIImagePNGRepresentation(selectVC.imageList[0])
        
        NetworkTools.tools.updateImage(urlString, parameters: parameters, imageData: imageData!) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("您还没有登录哦...")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发布成功...")
            
            
        }
        
//        NetworkTools.tools.requestJsonDict(.Post, urlString: urlString, parameters: parameters) { (result, error) -> () in
//            
//            if error != nil{
//                
//                SVProgressHUD.showErrorWithStatus("您的网络出错啦")
//                return
//            }
//            
//            SVProgressHUD.showSuccessWithStatus("发布微博成功...")
//            self.dismissViewControllerAnimated(true, completion: nil)
//            
//        }
        
        
    }

    override func viewDidLoad() {
        
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
        setTitleView()
        setupTextView()
        setToolBar()
        registerNotification()
        setupPictureSelect()
    }
    
  private func setupUI(){
    
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
    
    
    
    }
    //加载titleView
    private func setTitleView(){
        //设置titleView
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 40))
        //titleView.backgroundColor = UIColor.orangeColor()
        navigationItem.titleView = titleView
        
        let titleLabel : UILabel = UILabel(title: "发布微博", size: 15, color: UIColor.blackColor())
        let nameLabel : UILabel = UILabel(title: UserAccountViewModel().userName ?? "", size: 14, color: UIColor.blackColor())
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        //添加约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
    //加载textView
    private func setupTextView(){
        view.addSubview(textView)
        textView.backgroundColor = UIColor.lightGrayColor()
        
        textView.snp_makeConstraints { (make) -> Void in
            make.left.right.top.equalTo(view)
            make.height.equalTo(view.bounds.height / 3)
        }
        textView.addSubview(placeHolderLabel)
        
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
    }
    //加载图片选择器
    private func setupPictureSelect(){
        
        addChildViewController(selectVC)
        
        view.addSubview(selectVC.view)
        selectVC.view.snp_makeConstraints { (make) -> Void in
            
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(0)
        }
        
        
    }
    
    //懒加载
    
    lazy var textView : UITextView = {
       
        let textView = UITextView()
        textView.delegate = self
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.darkGrayColor()
        //设置键盘消失模式
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置弹簧效果开启
        textView.alwaysBounceVertical = true
        
        return textView
        
    }()
    
    //展位字符
    private lazy var placeHolderLabel : UILabel = UILabel(title: "发布新鲜事儿...", size: 18, color: UIColor.darkGrayColor())
    //工具条
    private lazy var toolBar : UIToolbar = UIToolbar()
    
    private lazy var selectVC : PictureSelectViewController = PictureSelectViewController()

}

extension ComposeViewController{
    
    //添加toolBar
    private func setToolBar(){
        
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(40)
        }
        //初始化一个UIBarButtonItem数组
        var items = [UIBarButtonItem]()
        
        let imageSettings = [["imageName" :"compose_toolbar_picture","actionName":"pictureSelect"],
            ["imageName" :"compose_mentionbutton_background"],
            ["imageName" :"compose_trendbutton_background"],
            ["imageName" :"compose_emoticonbutton_background"],
            ["imageName" :"compose_add_background"]]
        
        for dict in imageSettings{
            
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        items.removeLast()
        toolBar.items = items
        
    }
    //注册键盘通知
    private func registerNotification(){
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    //改变toolBar的高度
    @objc private func keyBoardWillChange(note:NSNotification){
        
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let rect = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    
}
//textView的代理方法
extension ComposeViewController : UITextViewDelegate{
    
    func textViewDidChangeSelection(textView:UITextView){
        
        placeHolderLabel.hidden = textView.hasText()
        
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
}
